package com.cow.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云示例
 */
@Component
@Slf4j
public class AIModelClient {

    @Value("${ai.dashscope.api-key}")
    private String apiKey;

    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    public String queryAI(String question) {
        Map<String, Object> body = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            body = new HashMap<>();
            Map<String, Object> input = new HashMap<>();
            input.put("prompt", question);

            body.put("model", "qwen-turbo");
            body.put("input", input);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(API_URL, entity, String.class);

            // 解析响应（示例，需根据实际API响应调整）
            JSONObject json = JSON.parseObject(response.getBody());
            return json.getJSONObject("output").getString("text");
        } catch (Exception e) {
            log.error("AI服务调用失败，原因：{}，请求参数：{}", e.getMessage(), body.toString());
            throw new RuntimeException("AI服务调用失败", e);
        }
    }
}
